package com.electronic.modules.other;

import com.electronic.api.R;
import com.electronic.exception.ResultCode;
import com.electronic.exception.ServiceException;
import com.electronic.modules.other.param.ReceiveAndSaveSignedFilePathDTO;
import com.electronic.modules.other.result.ReceiveAndSaveSignedFileHashVO;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 签章回调文件哈希
 * @author zyh 
 * ================================
 * Date: 2024/11/19
 * Time: 下午5:36
 * ================================
 */
public class ReceiveAndSaveSignedFileHashService {
    /**
     * 获取文件哈希
     * @param fileHashPath 文件地址
     * @return 文件哈希
     */
    public static R<ReceiveAndSaveSignedFileHashVO> getFileHash(ReceiveAndSaveSignedFilePathDTO fileHashPath) {
        // 返回值
        ReceiveAndSaveSignedFileHashVO receiveAndSaveSignedFileHashVO = new ReceiveAndSaveSignedFileHashVO();
        try {
            // 计算文件哈希
            if (fileHashPath.getSignatureFilePath() != null){
                receiveAndSaveSignedFileHashVO.setSignatureFileHash(DigestUtils.sha256Hex(new BufferedInputStream(Files.newInputStream(Paths.get(fileHashPath.getSignatureFilePath())))));;
            }
            if (fileHashPath.getAwaitingSignatureFilePath() != null){
                receiveAndSaveSignedFileHashVO.setAwaitingSignatureFileHash(DigestUtils.sha256Hex(new BufferedInputStream(Files.newInputStream(Paths.get(fileHashPath.getAwaitingSignatureFilePath())))));;
            }
        } catch (ServiceException | IOException e) {
            throw new ServiceException(ResultCode.ERROR_FILE,ResultCode.ERROR_FILE.getMessage());
        }
        return R.data(receiveAndSaveSignedFileHashVO);
    }

}